package com.bookmanger.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookmanger.common.result.Result;
import com.bookmanger.common.utils.UserIdThreadLocal;
import com.bookmanger.entity.Manager;
import com.bookmanger.entity.dto.AddMangerDTO;
import com.bookmanger.entity.dto.ManagerDTO;
import com.bookmanger.entity.select.ManagerListDto;
import com.bookmanger.entity.vo.ListForm;
import com.bookmanger.entity.vo.managerListVo;
import com.bookmanger.mapper.ManagerMapper;
import com.bookmanger.service.ManagerService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.bookmanger.common.utils.RedisConstants.LOGIN_MANAGER_KEY;
import static com.bookmanger.common.utils.RedisConstants.LOGIN_MANAGER_TTL;

/**
 * @author huangfuhao
 * @Date 2024/10/26
 */
@Service
@Slf4j
public class ManagerServiceImpl extends ServiceImpl<ManagerMapper, Manager> implements ManagerService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<ManagerDTO> login(Manager manager) {
        log.info("login: " + manager);
        String username = manager.getUsername();
        String password = manager.getPassword();

        //1.查找用户是否存在
        Manager one = lambdaQuery().eq(Manager::getUsername, username).one();
        if (one == null) {
            return Result.error("用户不存在");
        }

        //2.存在，判断密码是否正确
        String password1 = one.getPassword();
        if (!password.equals(password1)) {
            return Result.error("用户名或密码错误");
        }

        //3.保存用户信息到redis
        //3.1随机生成token，作为登录令牌
        String token = UUID.randomUUID().toString(true);
        //  3.2将Manager对象转为HashMap存储
        ManagerDTO managerDto = BeanUtil.copyProperties(one, ManagerDTO.class);
//        Map<String, Object> managerMap = BeanUtil.beanToMap(managerDto, new HashMap<>(),
//                CopyOptions.create()
//                        .setIgnoreNullValue(true)
//                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        //  3.3存储
        String tokenKey = LOGIN_MANAGER_KEY + token;
//        stringRedisTemplate.opsForHash().putAll(tokenKey, managerMap);
        //新的存储方式：存储用户id+权限
        stringRedisTemplate.opsForValue().set(tokenKey,one.getId()+"_manager");
        //  3.4设置token有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_MANAGER_TTL, TimeUnit.MINUTES);

        //  4.设置token
        managerDto.setAccessToken(token);
        managerDto.setRefreshToken(token);
        return Result.success(managerDto);
    }

    //TODO 未限定管理员
    @Override
    public Result<ListForm<managerListVo>> getManagerList(ManagerListDto managerListDto) {
        if(!extractedRootAdmin()){
            return Result.error("当前用户没有权限");
        }
        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        //用户名查询
        if (StringUtils.isNotBlank(managerListDto.getUsername())) {
            queryWrapper.eq("username", managerListDto.getUsername());
        }
        //状态查询
        if (managerListDto.getBanned() != null) {
            queryWrapper.eq("banned", managerListDto.getBanned());
        }
        Page<Manager> managerPage = new Page<>(managerListDto.getPage(), managerListDto.getSize());
        IPage<Manager> managerIPage = page(managerPage, queryWrapper);
        List<Manager> managerList = managerIPage.getRecords();
        List<managerListVo> managerListVoList = managerList.stream().map(manager -> {
            managerListVo vo = new managerListVo();
            BeanUtil.copyProperties(manager, vo);
            vo.setRole("admin");
            return vo;
        }).toList();
        ListForm<managerListVo> managerListForm = new ListForm<>(managerListDto.getPage(),managerListDto.getSize(),
                managerIPage.getPages(), //总页数
                managerIPage.getTotal(), //总记录数
                managerListVoList);
        return Result.success(managerListForm);
    }

    private boolean extractedRootAdmin() {
        Long adminId = UserIdThreadLocal.getUserId();
        log.info("adminId" + adminId.toString());
        //写死判断
        return adminId.equals(1L);
    }

    @Override
    public Result managerDisable(Long id) {
        if(!extractedRootAdmin()){
            return Result.error("当前用户没有权限");
        }
        if(baseMapper.selectById(id) == null) {
            return Result.error("id错误");
        }
        UpdateWrapper<Manager> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("banned", 2);
        boolean result = update(updateWrapper);
        if (result) {
            return Result.success("停用成功");
        } else {
            return Result.error("停用失败");
        }
    }

    @Override
    public Result managerEnable(Long id) {
        if(!extractedRootAdmin()){
            return Result.error("当前用户没有权限");
        }
        if(baseMapper.selectById(id) == null) {
            return Result.error("id错误");
        }
        UpdateWrapper<Manager> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("banned", 0);
        boolean result = update(updateWrapper);
        if (result) {
            return Result.success("启用成功");
        } else {
            return Result.error("启用失败");
        }
    }

    @Override
    public Result addManager(AddMangerDTO addMangerDTO) {
        if(!extractedRootAdmin()){
            return Result.error("当前用户没有权限");
        }
        if(!StringUtils.isNotBlank(addMangerDTO.getUsername())){
            return Result.error("用户名不能为空");
        }
        if(!StringUtils.isNotBlank(addMangerDTO.getPassword())){
            return Result.error("密码不能为空");
        }
        if (!isValidEmail(addMangerDTO.getEmail())) {
            return Result.error("邮箱格式不正确");
        }
        if(lambdaQuery().eq(Manager::getUsername, addMangerDTO.getUsername()).one() != null) {
            return Result.error("当前用户明已经存在");
        }
        Manager manager = new Manager();
        BeanUtil.copyProperties(addMangerDTO,manager);
        manager.setBanned(0);
        manager.setUpdateTime(LocalDateTime.now());
        int insert = baseMapper.insert(manager);
        if (insert != 0){
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    //验证邮箱格式
    private boolean isValidEmail(String email) {
        if (email == null || email.isEmpty()) {
            return false;
        }
        String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
        return email.matches(emailRegex);
    }
}
